package com.pandi.springboot_jwt.intercepter;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pandi.springboot_jwt.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author pandi
 * @create 2020-12-31 16:55
 * 这里是过滤所有Jwt携带的token,认证通过放行
 */
public class JWTIntercepter implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            if(verify.getClaim("account")!=null){
                return true;
            }
        }catch (Exception e){
            throw new JWTDecodeException("token失效或者token错误");
        }

        return false;
    }
}
